<template>
  <v-container>
    <!-- 加载状态 -->
    <div v-if="loading" class="text-center pa-10">
      <v-progress-circular indeterminate color="primary" size="64"></v-progress-circular>
      <p class="mt-4 text-grey-darken-1">正在为您生成专属运动计划...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="text-center pa-10">
      <v-alert type="error" dense>{{ error }}</v-alert>
    </div>

    <!-- 主体内容 -->
    <div v-else-if="editablePlan">
      <h1 class="text-h4 mb-2">{{ editablePlan.planName }}</h1>
      <p class="text-subtitle-1 text-grey-darken-1 mb-6">开始日期: {{ editablePlan.weekStartDate }}</p>

      <v-switch v-model="isEditMode" color="primary" label="编辑模式" inset class="mb-4"></v-switch>

      <v-expansion-panels v-model="openedPanels" variant="inset" class="custom-panels" multiple>
        <v-expansion-panel v-for="(day, dayIndex) in sortedDailyWorkouts" :key="day.dayOffset" :value="day.dayOffset">
          <v-expansion-panel-title>
            <v-row no-gutters class="align-center">
              <v-col cols="4" class="font-weight-bold">{{ formatDayOfWeek(day.dayOffset) }}</v-col>
              <v-col cols="5">{{ day.workoutName }}</v-col>
              <v-col cols="3" class="text-right">
                <v-btn v-if="day.workoutName !== '休息日' && day.isCompleted" color="success" size="small" prepend-icon="mdi-check-all" variant="tonal" disabled>已完成</v-btn>
                <v-btn v-else-if="day.workoutName !== '休息日' && !day.isCompleted" color="green" size="small" prepend-icon="mdi-check-circle" @click.stop="openLogDialog(day)" :loading="day.isLogging">完成打卡</v-btn>
                <v-icon v-else size="small">mdi-moon-waning-crescent</v-icon>
              </v-col>
            </v-row>
          </v-expansion-panel-title>

          <v-expansion-panel-text>
            <div v-if="day.workoutName === '休息日'" class="pa-4 text-center">
              <p>今天是休息日，让身体充分恢复！</p>
            </div>
            <!-- --- 核心修改：使用新的子组件 --- -->
            <v-list v-else lines="two">
              <ExerciseItem
                  v-for="(exercise, exIndex) in day.exercises"
                  :key="exercise.id"
                  :exercise="exercise"
                  :is-edit-mode="isEditMode"
                  @adjust-sets="delta => adjustSets(dayIndex, exIndex, delta)"
                  @remove="removeExercise(dayIndex, exIndex)"
                  @open-replace="openReplaceDialog(dayIndex, exIndex)"
                  @play-video="playVideo(exercise.videoUrl)"
              />
            </v-list>

            <v-card-actions v-if="isEditMode">
              <v-spacer></v-spacer>
              <v-btn variant="text" @click="cancelEditing(dayIndex)">取消</v-btn>
              <v-btn color="primary" @click="saveChanges(dayIndex)" :loading="day.isSaving">保存修改</v-btn>
            </v-card-actions>
          </v-expansion-panel-text>
        </v-expansion-panel>
      </v-expansion-panels>
    </div>

    <!-- Dialogs -->
    <v-dialog v-model="replaceDialog.show" max-width="600px" persistent>
      <v-card>
        <v-card-title>替换动作: {{ replaceDialog.originalExerciseName }}</v-card-title>
        <v-card-text style="min-height: 250px;">
          <div v-if="replaceDialog.isLoadingAlternatives" class="d-flex justify-center align-center fill-height">
            <HamsterLoader />
          </div>
          <v-list v-else>
            <v-list-item v-for="altEx in alternativeExercises" :key="altEx.id" :title="altEx.name" :subtitle="altEx.bodyPart" @click="replaceExercise(altEx)">
              <template v-slot:append><v-btn icon="mdi-plus" variant="text" color="primary"></v-btn></template>
            </v-list-item>
          </v-list>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="grey" variant="text" @click="replaceDialog.show = false">关闭</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- --- 运动打卡反馈对话框 --- -->
    <v-dialog v-model="logDialog.show" max-width="500px">
      <v-card>
        <v-card-title class="text-h5">记录你的训练</v-card-title>
        <v-card-text>
          <p class="mb-4">你对今天的 {{ logDialog.workoutName }} 感觉如何？</p>
          <v-rating
              v-model="logDialog.feedback"
              hover
              :item-labels="['太轻松', '', '刚刚好', '', '太累了']"
              :length="5"
              color="yellow-darken-3"
          ></v-rating>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn color="blue-darken-1" variant="text" @click="logDialog.show = false">取消</v-btn>
          <v-btn color="blue-darken-1" variant="text" @click="handleLogWorkout">确认记录</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- --- 解锁勋章祝贺对话框 --- -->
    <v-dialog v-model="badgeDialog.show" max-width="400px">
      <v-card class="text-center pa-4">
        <v-card-text>
          <v-icon size="64" color="amber">mdi-trophy-award</v-icon>
          <h2 class="text-h5 mt-4">恭喜！</h2>
          <p class="mt-2">你解锁了新勋章</p>
          <v-chip color="amber" class="mt-4 font-weight-bold">
            {{ badgeDialog.name }}
          </v-chip>
          <p class="mt-2 text-grey">{{ badgeDialog.description }}</p>
        </v-card-text>
        <v-card-actions>
          <v-btn color="primary" block @click="badgeDialog.show = false">太棒了！</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<script setup>
import { onMounted } from 'vue';
import { useWorkoutPlan } from '@/composables/useWorkoutPlan.js';
import ExerciseItem from '@/components/ExerciseItem.vue';
import HamsterLoader from '@/components/HamsterLoader.vue';

// 只需一行代码，即可获取所有状态和方法！
const {
  loading, error, editablePlan, isEditMode, sortedDailyWorkouts,
  openedPanels, logDialog, badgeDialog, replaceDialog, alternativeExercises,
  fetchWeeklyPlan, adjustSets, removeExercise, openReplaceDialog, replaceExercise,
  cancelEditing, saveChanges, openLogDialog, handleLogWorkout, playVideo, formatDayOfWeek,
} = useWorkoutPlan();

// 生命周期钩子
onMounted(fetchWeeklyPlan);
</script>


<style scoped>
.custom-panels .v-expansion-panel-title {
  font-size: 1.1rem;
}
</style>